//
//  ChatterViewController.m
//  ConferenceAppTab
//
//  Created by "Nadia on 3/24/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ChatterViewController.h"
#import "Post.h"

@interface ChatterViewController ()
- (NSUInteger)countUnreadPosts;
- (void)updateViewTitle;
- (void)feedChanged:(NSNotification *)notification;
- (void)feed2Changed:(NSNotification *)notification;
- (BOOL)postExists:(Post *)newPost;
@end

@implementation ChatterViewController

@synthesize feed, feed2, posts, nibLoadedCell;

#pragma mark -
#pragma mark View lifecycle


- (void)didDismissModalView {
	
    // Dismiss the modal view controller
	NSLog(@"Dismissing view");
	
    [self dismissModalViewControllerAnimated:YES];
	NSLog(@"Dismissed");
	
}

- (void)viewDidLoad {
    [super viewDidLoad];
	self.title=title;
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;

	//lifted from Rambler
	static NSString *feedURLString = @"feed://twitter.com/statuses/user_timeline/114054165.rss";
	static NSString *feedURLString2 = @"feed://search.twitter.com/search.atom?q=%23startrek";
	// make a URL obj using the string version
	NSURL *feedURL = [NSURL URLWithString:feedURLString];
	NSURL *feedURL2 = [NSURL URLWithString:feedURLString2];
	// make a new obj to get Post's from
	self.feed = [[Feed alloc] initWithURL:feedURL];
	self.feed2 = [[SearchFeed alloc] initWithURL:feedURL2];
	
	//make a new array to hold the posts we get from our URL / Feed
	self.posts = [[NSMutableArray alloc] init];
	
	// tell the Notification Center to add ME as an "observer" that should be notified whenever notifications
	//     are posted to the Center by the Feed object
    [[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(feedChanged:) // Hey notifyer: call *this* function, ok?
												 name:kFeederReloadCompletedNotification //...and this is what I want to know about
											   object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(feed2Changed:) // Hey notifyer: call *this* function, ok?
												 name:kSearchFeederReloadCompletedNotification //...and this is what I want to know about
											   object:nil];
	
	// now, trigger the network communication to get posts from the Feed
	[feed refresh];
	[feed2 refresh];
	
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	//[feed refresh];
	//[feed2 refresh];
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [posts count]-1;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
	// ID labels for the two different cell types in the Table
    //static NSString *postCellId = @"postCell";
	//static NSString *moreCellId = @"moreCell";
	
	// place to put the cell we make to return
	//UITableViewCell *cell = nil;
	
	// get local copies of the row number and the total number of rows
	NSUInteger row = [indexPath row];
	//NSUInteger count = [posts count]-1;
	
	// did system ask for the LASt row of the Table? [that's the "More..." row]
	/*if (row == count-1) {
	 
	 // get a recycled "More..." row cell, if one's available
	 cell = [tableView dequeueReusableCellWithIdentifier:moreCellId];
	 // if there's not an old one lying around, then make a new one
	 if (cell == nil) {
	 cell = [[[UITableViewCell alloc] 
	 initWithStyle:UITableViewCellStyleDefault // Note: "default" - a plain cell
	 reuseIdentifier:moreCellId] autorelease];
	 }
	 
	 // fill it in with stuff
	 cell.textLabel.text = @"Refresh...";
	 cell.textLabel.textColor = [UIColor grayColor];
	 cell.textLabel.font = [UIFont fontWithName: @"Georgia-Bold" size:18];
	 
	 // did the system ask for a regular, Post holding row?	
	 } else {*/
	
	// get an old, recycled one if one's available
	cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	// if we couldn't get an old one, make a new one
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] 
				 initWithStyle:UITableViewCellStyleDefault
				 reuseIdentifier:CellIdentifier] autorelease];
	}
	
	// get the Post that corresponds to the row the system requested
	//add 1 to skip the first post which is displayed above
	Post *currentPost = [posts objectAtIndex:row+1];
	
	
	// if this Post obj has already been read, then use reg font
	//    otherwise, use bold font
	if (currentPost.isRead) {
		cell.textLabel.font = [UIFont fontWithName: @"Helvetica" size:10];
	} else {
		cell.textLabel.font = [UIFont fontWithName: @"Helvetica-Bold" size:10];
	}
	
	// put Post's descript in "detail" part of cell, in smaller font
	// try this for MOMA site: (didn't work --- where's their XML?)
	//	    cell.detailTextLabel.text = [currentPost summary];
	//	    cell.detailTextLabel.text = [currentPost description];
	
	/*NSMutableString *string;
	string=[NSMutableString stringWithCapacity:150];
	[string appendString: @"#startrek "];
	[string appendString: [currentPost title]];*/
	
	cell.textLabel.text = [currentPost title];
	
	//cell.textLabel.font = [UIFont fontWithName: @"Arial" size: 12];
	//}
	
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
	
	NSUInteger row = [indexPath row];
	//NSUInteger count = [posts count];
	
	// did user want "More..."?
	/*if (row == count-1) {
	 
	 // refresh the list of Post's from the Feed
	 [feed refresh];
	 
	 // unselect the "More..." row
	 [self.postTable deselectRowAtIndexPath:indexPath animated:YES];
	 
	 // did user select a real Post?
	 } else {*/
	ChatterStatusWebViewController *statusView = [[ChatterStatusWebViewController alloc]init];
	statusView.delegate = self;
	
	statusView.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;	
	
	// Create a Navigation controller
	UINavigationController *navController = [[UINavigationController alloc]
											 initWithRootViewController:statusView];
	Post *currentPost = [posts objectAtIndex:row+1];
	// show the navigation controller modally
	[self presentModalViewController:navController animated:YES];
	statusView.title=[currentPost name];
	NSURL *url=[NSURL URLWithString:[currentPost link]];
	[statusView setURL:url];
	// Clean up resources
	[statusView release];
	[navController release];
	if (posts.count>0){
		
		// mark the Post as having been read
		currentPost.isRead = YES;
		
	}
	[currentPost release];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
	
	//lifted from Rambler
	self.feed = nil;	// kill the Feed obj
	self.feed2 = nil;
    self.posts = nil;	// kill the array of Posts
	[[NSNotificationCenter defaultCenter] removeObserver:self]; // don't even try to "notify" me any more
	
}


- (void)dealloc {
    [super dealloc];
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[feed release];
	[feed2 release];
    [posts release];
}

	
- (NSUInteger)countUnreadPosts {
		
		NSUInteger count = 0;
		for (Post *post in self.posts) {
			
			if (post.isRead == NO) {
				count++;
			}
		}
		
		return count;
}
	
	// updateViewTitle:
	// Change the view title to tell how many unread Posts there are
- (void)updateViewTitle {
		
		// any unreads?
		NSUInteger count = [self countUnreadPosts];
		
		// if yes, say how many in the title
		if (count) {
			self.title = [NSString stringWithFormat:@"Chatter (%u unread)", count];
			
			// if no, just generic title
		} else {
			self.title = @"Chatter";
		}
		
}
	
	// feedChanged:
	// BIG DEAL: This is the function we told the Notificatino Center to call whenever 
	//    a Feed read is successfully completed!
- (void)feedChanged:(NSNotification *)notification {
		
		// assume there's no change to the list of Posts, until further notice
		BOOL newPost = NO;
		
		// get the current list of Posts from our Feed obj
		NSMutableArray *feedPosts = [feed feedPosts];
		// loop through my currently known posts...
		for (Post *feedPost in feedPosts) {
			
			// haven I not seen this Post before?
			if (![self postExists:feedPost]) {
				newPost = YES;	// then it's new
				[posts addObject:feedPost]; //...and I need to add it to my array of known Posts
			}
		}
		
		// [after loop...]
		// are there any new Posts?
		if (newPost) {
			
			// if so, reload the table of Posts
			[self.tableView reloadData];
			
			//...and update the title (...to show how many Posts are unread)
			[self updateViewTitle];
		}
	//[feed2 refresh];
}

- (void)feed2Changed:(NSNotification *)notification {
	
	// assume there's no change to the list of Posts, until further notice
	BOOL newPost = NO;
	
	// get the current list of Posts from our Feed2 obj
	NSMutableArray *feed2Posts = [feed2 feedPosts];
	// loop through my currently known posts...
	for (Post *feedPost in feed2Posts) {
		
		// haven I not seen this Post before?
		if (![self postExists:feedPost]) {
			newPost = YES;	// then it's new
			[posts addObject:feedPost]; //...and I need to add it to my array of known Posts
		}
	}
	
	// [after loop...]
	// are there any new Posts?
	if (newPost) {
		
		// if so, reload the table of Posts
		[self.tableView reloadData];
		
		//...and update the title (...to show how many Posts are unread)
		[self updateViewTitle];
	}
}

	
	// newPost:
	// Q: Is this Post already in my array of Posts?
- (BOOL)postExists:(Post *)newPost {
		
		// just compare title fields in posts
		NSString *tubby = [newPost title];
		
		// see if it matches a title I already know...
		for (Post *post in self.posts) {
			
			if ([post.title isEqualToString:tubby]) {
				return YES;
			}
		}
		
		return NO;
}
	

@end

